package com.ruoyi.business.controller;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.ruoyi.business.domain.MroLogistics;
import com.ruoyi.business.dto.CheckMorLogisticsDto;
import com.ruoyi.business.listener.LogisticsInfoExcelListener;
import com.ruoyi.business.service.IMroLogisticsService;
import com.ruoyi.business.utils.CommonResult;
import com.ruoyi.business.utils.MyExcelUtil;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.DictUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import org.apache.poi.ss.usermodel.DataValidation;
import org.apache.poi.ss.usermodel.DataValidationConstraint;
import org.apache.poi.ss.usermodel.DataValidationHelper;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.util.CellRangeAddressList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 物流信息Controller
 *
 * @author wyb
 * @date 2025-07-28
 */
@RestController
@RequestMapping("/Logistics/logistics")
public class MroLogisticsController extends BaseController {
    @Autowired
    private IMroLogisticsService mroLogisticsService;

    /**
     * 查询物流信息列表
     */
    @PreAuthorize("@ss.hasPermi('Logistics:logistics:list')")
    @GetMapping("/list")
    public TableDataInfo list(MroLogistics mroLogistics) {
        startPage();
        List<MroLogistics> list = mroLogisticsService.selectMroLogisticsList(mroLogistics);
        return getDataTable(list);
    }

    /**
     * 导出物流信息列表
     */
    @PreAuthorize("@ss.hasPermi('Logistics:logistics:export')")
    @Log(title = "物流信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, MroLogistics mroLogistics) {
        List<MroLogistics> list = mroLogisticsService.selectMroLogisticsList(mroLogistics);
        ExcelUtil<MroLogistics> util = new ExcelUtil<MroLogistics>(MroLogistics.class);
        util.exportExcel(response, list, "物流信息数据");
    }

    /**
     * 获取物流信息详细信息
     */
    @PreAuthorize("@ss.hasPermi('Logistics:logistics:query')")
    @GetMapping(value = "/{deliveryNo}")
    public AjaxResult getInfo(@PathVariable("deliveryNo") String deliveryNo) {
        return success(mroLogisticsService.selectMroLogisticsByDeliveryNo(deliveryNo));
    }

    /**
     * 新增物流信息
     */
    @PreAuthorize("@ss.hasPermi('Logistics:logistics:add')")
    @Log(title = "物流信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody MroLogistics mroLogistics) {
        return toAjax(mroLogisticsService.insertMroLogistics(mroLogistics));
    }

    /**
     * 修改物流信息
     */
    @PreAuthorize("@ss.hasPermi('Logistics:logistics:edit')")
    @Log(title = "物流信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody MroLogistics mroLogistics) {
        return toAjax(mroLogisticsService.updateMroLogistics(mroLogistics));
    }

    /**
     * 删除物流信息
     */
    @PreAuthorize("@ss.hasPermi('Logistics:logistics:remove')")
    @Log(title = "物流信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{deliveryNos}")
    public AjaxResult remove(@PathVariable String[] deliveryNos) {
        return toAjax(mroLogisticsService.deleteMroLogisticsByDeliveryNos(deliveryNos));
    }


    /*物流下载模板
     * */
    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) throws UnsupportedEncodingException {
        ExcelUtil<CheckMorLogisticsDto> util = new ExcelUtil<CheckMorLogisticsDto>(CheckMorLogisticsDto.class);
        // 获取数据字典列表
        List<SysDictData> logisticsCompanyList = DictUtils.getDictCache("sys_logistics_company");
        // 物流公司名称集合
        List<String> logisticsCompanyLabels = logisticsCompanyList.stream().map(SysDictData::getDictLabel).collect(Collectors.toList());
        // 生成包含数据验证的模板
        try (ExcelWriter excelWriter = MyExcelUtil.getExcelWriter(response.getOutputStream())) {
            // 创建工作表
            WriteSheet writeSheet = EasyExcel.writerSheet("Sheet1").head(CheckMorLogisticsDto.class).build();
            // 先写入空数据以初始化Sheet
            excelWriter.write(new ArrayList<>(), writeSheet);
            // 获取实际的Sheet对象
            Sheet sheet = excelWriter.writeContext().writeSheetHolder().getSheet();
            // 添加数据验证
            DataValidationHelper helper = sheet.getDataValidationHelper();
            DataValidationConstraint constraint = helper.createExplicitListConstraint(logisticsCompanyLabels.toArray(new String[0]));
            // 假设要在第4列添加数据字典下拉框
            CellRangeAddressList addressList = new CellRangeAddressList(1, 1000, 2, 2); // 行,行,列,列
            DataValidation validation = helper.createValidation(constraint, addressList);
            sheet.addValidationData(validation);
            excelWriter.write(new ArrayList<>(), writeSheet);
        } catch (IOException e) {
            e.printStackTrace();
        }
        util.importTemplateExcel(response, "物流数据");
    }


    /**
     * 导入excel物流信息
     *
     * @param file
     * @return
     */
    @PreAuthorize("@ss.hasPermi('Logistics:logistics:import')")
    @Log(title = "物流信息", businessType = BusinessType.IMPORT)
    @PostMapping("/importMorLogisticsInfoFile")
    @ResponseBody
    public CommonResult importBuyerInfoFile(@RequestParam("file") MultipartFile file) throws IOException {
        LogisticsInfoExcelListener listener = new LogisticsInfoExcelListener(mroLogisticsService);
        EasyExcel.read(file.getInputStream(), listener)
                .sheet()
                .headRowNumber(1)
                .doRead();
        List<String> errorList = listener.errorList;
        if (CollUtil.isNotEmpty(errorList)) {
            return CommonResult.failed("导入失败,请检查:" + listener.errorList);
        } else {
            return CommonResult.success(null);
        }
    }

    /**
     * 获取物流管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('Logistics:logistics:query')")
    @GetMapping(value = "/getLogisticsInfo/{deliveryNo}")
    public AjaxResult getLogisticsInfo(@PathVariable("deliveryNo") String deliveryNo) {
        return success(mroLogisticsService.selectLogisticsInfoByDeliveryNo(deliveryNo));
    }

    @GetMapping(value = "/getLogisticsInfoByOuterOrderNo/{outerOrderNo}")
    public AjaxResult getLogisticsInfoByOuterOrderNo(@PathVariable("outerOrderNo") String outerOrderNo) {
        return success(mroLogisticsService.getLogisticsInfoByOuterOrderNo(outerOrderNo));
    }


    /*去重后的物流集合*/
    @GetMapping(value = "/distinctMroLogisticsList")
    public TableDataInfo distinctList(MroLogistics mroLogistics) {
        startPage();
        List<MroLogistics> list = mroLogisticsService.distinctList(mroLogistics);
        return getDataTable(list);
    }
}
